package com.way.pm25;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.way.pm25.anim.PM25Anim;
import com.way.pm25.util.L;
import com.way.pm25.util.NetUtil;
import com.way.pm25.util.PM25Geocoder;
import com.way.pm25.util.PM25Geocoder.CityNameStatus;
import com.way.pm25.util.PM25Provider;

/**
 * 主界面，完成各种操作。
 * 
 * @author way
 * 
 */
public class PM25Activity extends Activity implements OnClickListener,
		OnLongClickListener, OnKeyListener, OnTouchListener {
	private static final String TAG = "pm25";
	private PM25Geocoder mPm25Geocoder;
	private static Map<String, String> mAdviceMaps = new HashMap<String, String>();
	private static float x;
	private Boolean mIsCanPrint = false;
	private Boolean mIsCanRip = false;
	private int mCityIndex = 0;
	private Boolean mIsAbout = false;
	private Boolean mIsCitySwitching = false;
	private Boolean mIsFeedback = false;
	private Boolean mIsFirst = true;
	private TextView mAQITextView;
	private Animation mAlphaAnim = new AlphaAnimation(0.1F, 1.0F);
	private ViewGroup mBodyViewGroup;
	private Animator mBodyResetAnim;
	private Animator mBodyTranslateAnim;
	private TextView mByTextView;
	private TextView mCityTextView;
	private Animator mFeedbackSendedAnim;
	private ListView mListView;
	private ImageButton mNextBtn;
	private TextView mPM25TextView;
	private TextView mPaperAQITextView;
	private TextView mPaperAQIDescTextView;
	private TextView mPaperAreaTextView;
	private TextView mPaperDividerTextView1;
	private TextView mPaperDividerTextView2;
	private TextView mPaperFeedbackDescTextView;
	private EditText mPaperFeedbackMessageEditView;
	private TextView mPaperFeedbackTitleTextView;
	private ViewGroup mPaperViewGroup;
	private ViewGroup mPaperListViewGroup;
	private TextView mPaperProposalTextView;
	private TextView mPaperQualityTextView;
	private TextView mPaperShareFromTextView;
	private TextView mPaperTimeTextView;
	private TextView mPaperTitleTextView;
	private TextView mLoTextView;
	private Animator mPaperUpAll;
	private Animator mPaperUpTitle;
	private ImageButton mPrintBtn;
	private MediaPlayer mPrintPlayer;
	private MediaPlayer mRipPlayer;
	private PM25CitySetting mSetting;
	private ImageButton mShareBtn;
	private TextView mStudioTextView;
	private TextView mValueTextView;
	private ViewGroup mRootView;
	private String mAQIStr;
	private String mBeforeCity;
	private String mCurCity;
	private String mPM25Str;
	private String mQualityStr;
	private String mShareStr = "今日%s空气质量指数(AQI)：%s，等级【%s】；PM2.5 浓度值：%s μg/m3。%s。（请关注博客：http://bL.csdn.net/way_ping_li ）";
	private String mTimestr;
	private Resources mResources;
	private InputMethodManager mInputMethodManager;

	static {
		mAdviceMaps.put("优", "空气特别好，尽情活动吧");
		mAdviceMaps.put("良", "仅对特别敏感患者轻微影响");
		mAdviceMaps.put("轻度污染", "易感人群勿长期户外活动");
		mAdviceMaps.put("中度污染", "可能影响心脏、呼吸系统");
		mAdviceMaps.put("重度污染", "心脏病和肺病患者症状加剧");
		mAdviceMaps.put("严重污染", "所有人尽量避免户外活动");
	}

	private void disableAbout() {
		mAQITextView.setVisibility(View.VISIBLE);
		mPM25TextView.setVisibility(View.VISIBLE);
		mValueTextView.setVisibility(View.VISIBLE);
		mByTextView.setVisibility(View.GONE);
		mStudioTextView.setVisibility(View.GONE);
		mCityTextView.setText(this.mBeforeCity);
	}

	private void disablePaperFeedback() {
		mPaperTitleTextView.setVisibility(View.VISIBLE);
		mPaperAQIDescTextView.setVisibility(View.VISIBLE);
		mPaperAreaTextView.setVisibility(View.VISIBLE);
		mPaperAQITextView.setVisibility(View.VISIBLE);
		mPaperQualityTextView.setVisibility(View.VISIBLE);
		mPaperTimeTextView.setVisibility(View.VISIBLE);
		mPaperProposalTextView.setVisibility(View.VISIBLE);
		mPaperListViewGroup.setVisibility(View.VISIBLE);
		mListView.setVisibility(View.VISIBLE);
		mPaperShareFromTextView.setVisibility(View.VISIBLE);
		mPaperDividerTextView1.setVisibility(View.VISIBLE);
		mPaperDividerTextView2.setVisibility(View.VISIBLE);
		mPaperViewGroup.setAlpha(1.0F);
		mPaperFeedbackMessageEditView.setVisibility(View.GONE);
		mPaperFeedbackTitleTextView.setVisibility(View.GONE);
		mPaperFeedbackDescTextView.setVisibility(View.GONE);
	}

	private void enableAbout() {
		mAQITextView.setVisibility(View.GONE);
		mPM25TextView.setVisibility(View.GONE);
		mValueTextView.setVisibility(View.GONE);
		mByTextView.setVisibility(View.VISIBLE);
		mStudioTextView.setVisibility(View.VISIBLE);
		mBeforeCity = this.mCityTextView.getText().toString();
		mCityTextView.setText("way_ping_li");
	}

	private void enableButtonControls(boolean enabled) {
		mNextBtn.setEnabled(enabled);
		mPrintBtn.setEnabled(enabled);
	}

	private void enablePaperFeedback() {
		mPaperTitleTextView.setVisibility(View.GONE);
		mPaperAQIDescTextView.setVisibility(View.GONE);
		mPaperAreaTextView.setVisibility(View.GONE);
		mPaperAQITextView.setVisibility(View.GONE);
		mPaperQualityTextView.setVisibility(View.GONE);
		mPaperTimeTextView.setVisibility(View.GONE);
		mPaperProposalTextView.setVisibility(View.GONE);
		mPaperListViewGroup.setVisibility(View.GONE);
		mListView.setVisibility(View.GONE);
		mPaperShareFromTextView.setVisibility(View.GONE);
		mPaperDividerTextView1.setVisibility(View.GONE);
		mPaperDividerTextView2.setVisibility(View.GONE);
		mPaperFeedbackMessageEditView.setVisibility(View.VISIBLE);
		mPaperFeedbackTitleTextView.setVisibility(View.VISIBLE);
		mPaperFeedbackDescTextView.setVisibility(View.VISIBLE);
	}

	private void initFontface() {
		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"fonts/LCD.ttf");
		mCityTextView.setTypeface(typeface);
		mAQITextView.setTypeface(typeface);
		mPM25TextView.setTypeface(typeface);
		mValueTextView.setTypeface(typeface);
		mByTextView.setTypeface(typeface);
		mStudioTextView.setTypeface(typeface);
	}

	private void initPlayer() {
		mPrintPlayer = MediaPlayer.create(this, R.raw.print);
		mPrintPlayer.setLooping(true);
		mRipPlayer = MediaPlayer.create(this, R.raw.paper_rip);
	}

	private void initViewAndLayout() {
		mBodyViewGroup = ((ViewGroup) findViewById(R.id.layout_main));
		mPaperViewGroup = ((ViewGroup) findViewById(R.id.layout_ticket_out));
		mRootView = ((ViewGroup) findViewById(R.id.rl));
		mPaperListViewGroup = ((ViewGroup) findViewById(R.id.layout_paper_list_header));
		mCityTextView = ((TextView) findViewById(R.id.txt_city_value));
		mAQITextView = ((TextView) findViewById(R.id.txt_aqi_desc));
		mPM25TextView = ((TextView) findViewById(R.id.txt_pm25_desc));
		mValueTextView = ((TextView) findViewById(R.id.txt_value));
		mAQITextView.setVisibility(View.GONE);
		mPM25TextView.setVisibility(View.GONE);
		mValueTextView.setVisibility(View.GONE);
		mLoTextView = (TextView) findViewById(R.id.img_logo);
		mShareBtn = ((ImageButton) findViewById(R.id.btn_paper_share));
		mNextBtn = ((ImageButton) findViewById(R.id.btn_next));
		mPrintBtn = ((ImageButton) findViewById(R.id.btn_print));
		mByTextView = ((TextView) findViewById(R.id.txt_led_by));
		mStudioTextView = ((TextView) findViewById(R.id.txt_led_studio));
		mListView = ((ListView) mPaperViewGroup.findViewById(R.id.paper_list));
		mPaperAQITextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_aqi_value));
		mPaperAreaTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_area));
		mPaperTimeTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_datetime));
		mPaperQualityTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_quality));
		mPaperProposalTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_proposal));
		mPaperTitleTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_report));
		mPaperAQIDescTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_aqi_desc));
		mPaperShareFromTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_share_from));
		mPaperDividerTextView1 = ((TextView) mPaperViewGroup
				.findViewById(R.id.divide1));
		mPaperDividerTextView2 = ((TextView) mPaperViewGroup
				.findViewById(R.id.divide2));
		mPaperFeedbackMessageEditView = ((EditText) mPaperViewGroup
				.findViewById(R.id.txt_paper_feedback_message));
		mPaperFeedbackTitleTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_feedback_title));
		mPaperFeedbackDescTextView = ((TextView) mPaperViewGroup
				.findViewById(R.id.txt_paper_feedback_desc));

	}

	private void postFeedback(String feedbackMessage) {
		Intent email = new Intent(Intent.ACTION_SENDTO);
		email.setData(Uri.parse("mailto:way.ping.li@gmail.com"));
		email.putExtra(Intent.EXTRA_SUBJECT, "pm25反馈");
		email.putExtra(Intent.EXTRA_TEXT, feedbackMessage);
		startActivity(email);
		// new PostTask(
		// "http://www.pm25.in/api/update/feedback.json?token=4esfG6UEhGzNkbszfjAp&city")
		// .execute(new String[] { feedbackMessage });
		mPaperFeedbackMessageEditView.setText("");
	}

	private void selectCity() {
		if (mCityIndex < API.CITIES.length) {
			mCityTextView.setText(wrapFont(API.CITIES[mCityIndex]));
			mCityIndex = (1 + mCityIndex);
			return;
		}
		mCityIndex = 1;
	}

	private void shareTo() {
		try {
			new File(getFilesDir(), "share.png").deleteOnExit();
			FileOutputStream fileOutputStream = openFileOutput("share.png", 1);
			mPaperViewGroup.setDrawingCacheEnabled(true);
			mPaperViewGroup.getDrawingCache().compress(
					Bitmap.CompressFormat.PNG, 100, fileOutputStream);
			File file = new File(getFilesDir(), "share.png");
			Object[] objects = new Object[] { mCurCity, mAQIStr, mQualityStr,
					mPM25Str, mAdviceMaps.get(mQualityStr) };
			Intent intent = new Intent("android.intent.action.SEND");
			intent.setType("image/*");
			intent.putExtra("sms_body", String.format(mShareStr, objects));
			intent.putExtra("android.intent.extra.TEXT",
					String.format(mShareStr, objects));
			intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(file));
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(Intent.createChooser(intent, "分享到"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void startInfoShow() {
		// mAQITextView.setAnimation(mAlphaAnim);
		// mPM25TextView.setAnimation(mAlphaAnim);
		mValueTextView.setAnimation(mAlphaAnim);
		mAlphaAnim.setRepeatCount(2);
		mAlphaAnim.setDuration(300L);
		mAlphaAnim.setAnimationListener(new Animation.AnimationListener() {
			public void onAnimationEnd(Animation animation) {
				mAQITextView.setVisibility(View.VISIBLE);
				mPM25TextView.setVisibility(View.VISIBLE);
				mAQITextView.setText(" = AQI ");
				mPM25TextView.setText("    PM2.5 /H");
				mValueTextView.setText(mAQIStr);
				mIsCanPrint = true;
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationStart(Animation animation) {
			}
		});
		mAlphaAnim.start();
	}

	private void startPaperAnimation() {
		RelativeLayout.LayoutParams relativeLayoutParams = (RelativeLayout.LayoutParams) mPaperViewGroup
				.getLayoutParams();
		L.d(TAG,
				String.format("paperLP.height %s", relativeLayoutParams.height));
		relativeLayoutParams.height = getResources().getDimensionPixelSize(
				R.dimen.paper_height);
		L.d(TAG,
				String.format("paperLP.height %s", relativeLayoutParams.height));
		mPaperViewGroup.setLayoutParams(relativeLayoutParams);
		AnimatorSet animatorSet = new AnimatorSet();
		Animator[] animators = new Animator[3];
		animators[0] = mPaperUpTitle;
		animators[1] = mBodyTranslateAnim;
		animators[2] = mPaperUpAll;
		animatorSet.playSequentially(animators);
		animatorSet.addListener(new Animator.AnimatorListener() {
			public void onAnimationCancel(Animator paramAnonymousAnimator) {
			}

			public void onAnimationEnd(Animator paramAnonymousAnimator) {
				if (!mIsFeedback)
					mShareBtn.setVisibility(View.VISIBLE);
				mIsCanRip = true;
			}

			public void onAnimationRepeat(Animator paramAnonymousAnimator) {
			}

			public void onAnimationStart(Animator paramAnonymousAnimator) {
			}
		});
		animatorSet.start();
	}

	private void updateAQI_PM25(String city) {
		L.d(TAG, String.format("update city : %s", city));
		mAQIStr = "error ";
		mValueTextView.setText(mAQIStr);
		// mAQITextView.setVisibility(View.VISIBLE);
		// mPM25TextView.setVisibility(View.VISIBLE);
		// mValueTextView.setVisibility(View.VISIBLE);
		if (city.equalsIgnoreCase("auto"))
			city = mSetting.getAutoCity();
		new PM25Provider().request(new PM25Provider.PM25Info() {
			@Override
			public void onPreExecute() {
				// Toast.makeText(PM25Activity.this, "begin...",
				// Toast.LENGTH_SHORT).show();
				enableButtonControls(false);
				mAQITextView.setVisibility(View.GONE);
				mPM25TextView.setVisibility(View.GONE);
				mValueTextView.setVisibility(View.VISIBLE);
				mValueTextView.setText(" wait ");

				mAlphaAnim.setDuration(100L);
				mAlphaAnim.setRepeatCount(-1);
				mValueTextView.setAnimation(mAlphaAnim);
				mAlphaAnim.start();
			}

			@Override
			public void onInfo(List<PM25Provider.PM25> pm25List) {
				enableButtonControls(true);
				if (pm25List == null) {
					Toast.makeText(PM25Activity.this, R.string.get_pm25_fail,
							Toast.LENGTH_SHORT).show();
					return;
				}
				PM25Provider.PM25 pm25 = (PM25Provider.PM25) pm25List.get(-1
						+ pm25List.size());
				mAQIStr = wrapFont(pm25.aqi);
				mPM25Str = wrapFont(pm25.pm2_5);
				mPaperAQITextView.setText(mAQIStr);
				try {
					Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
							.parse(pm25.time_point);
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyy年MM月dd日 HH:mm");
					mTimestr = sdf.format(date);
					mPaperTimeTextView.setText("发布时间:" + mTimestr);
					mCurCity = pm25.area;
					mPaperAreaTextView.setText(mCurCity);
					mQualityStr = pm25.quality;
					mPaperQualityTextView.setText("等级:" + mQualityStr);
					mPaperProposalTextView.setText("建议:"
							+ mAdviceMaps.get(mQualityStr));

					mValueTextView.setAnimation(null);
					mValueTextView.setText("  ok  ");
					mListView.setAdapter(new PM25Adapter(PM25Activity.this,
							pm25List));
					startInfoShow();
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}

		}, city);
	}

	private String wrapFont(String paramString) {
		return paramString + " ";
	}

	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.main);
		mSetting = new PM25CitySetting(this);
		mResources = getResources();
		mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		initViewAndLayout();
		initFontface();
		initPlayer();
		// 用来调整mBodyViewGroup和mPaperViewGroup高度
		mRootView.getViewTreeObserver().addOnGlobalLayoutListener(
				new ViewTreeObserver.OnGlobalLayoutListener() {
					public void onGlobalLayout() {
						int rootViewHeight = getWindow().findViewById(R.id.rl)
								.getHeight();
						L.d(TAG, "device height :"
								+ getWindow().getDecorView().getHeight());
						L.d(TAG, "onGlobalLayout:" + rootViewHeight);
						mRootView.setLayoutParams(new FrameLayout.LayoutParams(
								-1, rootViewHeight * 3));
						mRootView.setPadding(0, -rootViewHeight, 0,
								rootViewHeight);
						RelativeLayout.LayoutParams bodyLayoutParams = (RelativeLayout.LayoutParams) mBodyViewGroup
								.getLayoutParams();
						bodyLayoutParams.height = (rootViewHeight * 2);
						bodyLayoutParams.setMargins(0, 0, 0, -rootViewHeight);
						mBodyViewGroup.setLayoutParams(bodyLayoutParams);
						RelativeLayout.LayoutParams paperLayoutParams = (RelativeLayout.LayoutParams) mPaperViewGroup
								.getLayoutParams();
						paperLayoutParams.height = (rootViewHeight * 2);
						paperLayoutParams.setMargins(
								0,
								mResources
										.getDimensionPixelSize(R.dimen.main_paper_margin_top),
								0,
								mResources
										.getDimensionPixelSize(R.dimen.main_paper_margin_bottom));
						mPaperViewGroup.setLayoutParams(paperLayoutParams);
						mRootView.getViewTreeObserver()
								.removeGlobalOnLayoutListener(this);
					}
				});
		// 整体移动动画
		mBodyTranslateAnim = PM25Anim.down(mBodyViewGroup,
				mResources.getDimension(R.dimen.paper_anim_down));
		// 纸张标题移动动画
		mPaperUpTitle = PM25Anim.up(mPaperViewGroup,
				mResources.getDimension(R.dimen.paper_anim_up_one));
		// 整张纸移动动画
		mPaperUpAll = PM25Anim.up(mPaperViewGroup,
				getResources().getDimension(R.dimen.paper_anim_up_one),
				getResources().getDimension(R.dimen.paper_anim_up_two));
		// 反馈消息移动动画
		mFeedbackSendedAnim = PM25Anim.upAndVanish(mPaperViewGroup,
				getResources().getDimension(R.dimen.paper_anim_up_two));
		// 恢复原状移动动画
		mBodyResetAnim = PM25Anim.up(mBodyViewGroup, getResources()
				.getDimension(R.dimen.paper_anim_down), 0.0F);
		// 反馈动画监听
		mFeedbackSendedAnim.addListener(new Animator.AnimatorListener() {
			public void onAnimationCancel(Animator animator) {
			}

			public void onAnimationEnd(Animator animator) {
				mBodyResetAnim.start();
				disablePaperFeedback();
			}

			public void onAnimationRepeat(Animator animator) {
			}

			public void onAnimationStart(Animator animator) {
			}
		});
		// 打印动画监听，用来控制播放声音
		Animator.AnimatorListener printAnimatorListener = new Animator.AnimatorListener() {
			public void onAnimationCancel(Animator animator) {
			}

			public void onAnimationEnd(Animator animator) {
				mPrintPlayer.pause();
			}

			public void onAnimationRepeat(Animator animator) {
			}

			public void onAnimationStart(Animator animator) {
				mPrintPlayer.start();
			}
		};
		mPaperUpAll.addListener(printAnimatorListener);
		mPaperUpTitle.addListener(printAnimatorListener);
		// N键点击事件
		mNextBtn.setOnClickListener(this);
		// N键长按事件
		mNextBtn.setOnLongClickListener(this);
		mAlphaAnim.setDuration(100L);
		mAlphaAnim.setRepeatCount(-1);
		mCityTextView.setAnimation(mAlphaAnim);
		// P键点击事件
		mPrintBtn.setOnClickListener(this);
		// P键长按事件
		mPrintBtn.setOnLongClickListener(this);
		// 分享按钮点击事件
		mShareBtn.setOnClickListener(this);
		// 撕掉纸张的动画
		mPaperViewGroup.setOnTouchListener(this);
		// 反馈消息编辑框事件监听
		mPaperFeedbackMessageEditView.setOnKeyListener(this);
		// 恢复原始状态动画监听
		mBodyResetAnim.addListener(new Animator.AnimatorListener() {
			public void onAnimationCancel(Animator animator) {
			}

			public void onAnimationEnd(Animator animator) {
				disablePaperFeedback();
			}

			public void onAnimationRepeat(Animator animator) {
			}

			public void onAnimationStart(Animator animator) {
			}
		});
	}

	@Override
	public boolean onTouch(final View view, MotionEvent event) {
		if (!mIsCanRip)// 如果不能撕，直接返回
			return false;
		mShareBtn.setVisibility(View.GONE);
		if (Build.VERSION.SDK_INT >= 11) {// 只有3.0以上的api才能使用。
			if (event.getAction() == MotionEvent.ACTION_DOWN)
				x = event.getX();
			if (event.getAction() == MotionEvent.ACTION_MOVE) {
				if (view.getRotation() > 0.0F)
					view.setPivotX(view.getWidth());
				if (view.getRotation() < 0.0F)
					view.setPivotX(0.0F);
				view.setPivotY(view.getHeight());
				view.setRotation(view.getRotation() + (event.getX() - x)
						/ 50.0F);
			}
			if (event.getAction() == MotionEvent.ACTION_UP) {
				L.d(TAG,
						String.format("getRotation : %s", view.getRotation()));
				Animator.AnimatorListener ripAnimator = new Animator.AnimatorListener() {
					public void onAnimationCancel(Animator animator) {
					}

					public void onAnimationEnd(Animator animator) {
						mBodyResetAnim.start();
						view.setTranslationY(0.0F);
						view.setRotation(0.0F);
						view.setAlpha(1.0F);
						mIsCanRip = false;
					}

					public void onAnimationRepeat(Animator animator) {
					}

					public void onAnimationStart(Animator animator) {
						mRipPlayer.start();
					}
				};
				if (Math.abs(view.getRotation()) <= 3.0F)
					view.setRotation(0.0F);
				if (view.getRotation() > 3.0F) {
					ViewPropertyAnimator.animate(view).setDuration(1000L)
							.alpha(0.0F).rotation(90.0F)
							.setListener(ripAnimator).start();
				} else if (view.getRotation() < -3.0F) {
					ViewPropertyAnimator.animate(view).setDuration(1000L)
							.alpha(0.0F).rotation(-90.0F)
							.setListener(ripAnimator).start();
				} else {
					if (!mIsFeedback)
						mShareBtn.setVisibility(View.VISIBLE);
				}
			}
		}
		return false;
	}

	@Override
	public boolean onKey(View view, int keyCode, KeyEvent event) {
		if ((KeyEvent.KEYCODE_ENTER == keyCode)
				&& (event.getAction() == KeyEvent.ACTION_DOWN)) {
			L.d(TAG, "send to");
			String feedbackMessage = mPaperFeedbackMessageEditView.getText()
					.toString();
			L.d(TAG, feedbackMessage);
			if (TextUtils.isEmpty(feedbackMessage)
					|| feedbackMessage.length() < 5) {
				Toast.makeText(PM25Activity.this,
						R.string.feedback_can_not_null, Toast.LENGTH_SHORT)
						.show();
				return true;
			}
			postFeedback(feedbackMessage);
			mInputMethodManager.hideSoftInputFromWindow(
					view.getApplicationWindowToken(), 2);
			mFeedbackSendedAnim.start();
			return true;
		}
		return false;
	}

	@Override
	public boolean onLongClick(View v) {
		switch (v.getId()) {
		case R.id.btn_next:// 长按N键事件处理
			if (mIsCitySwitching) {
				mIsCitySwitching = false;
				mAQITextView.setVisibility(View.VISIBLE);
				mPM25TextView.setVisibility(View.VISIBLE);
				mValueTextView.setVisibility(View.VISIBLE);
				mCityTextView.setAnimation(null);
				mCityTextView.setText(mBeforeCity);
				return true;
			}
			mIsCitySwitching = true;
			mIsCanPrint = false;
			mAQITextView.setVisibility(View.GONE);
			mPM25TextView.setVisibility(View.GONE);
			mValueTextView.setVisibility(View.GONE);
			mValueTextView.setAnimation(null);
			mBeforeCity = mCityTextView.getText().toString().trim();
			mCityIndex = 1;// 位置重置
			mCityTextView.setText(API.CITIES[0]);
			mAlphaAnim.setDuration(500L);
			mAlphaAnim.setRepeatCount(-1);
			mCityTextView.setAnimation(mAlphaAnim);
			mAlphaAnim.start();
			return true;
		case R.id.btn_print:// 长按P键事件处理
			mIsFeedback = true;
			enablePaperFeedback();
			startPaperAnimation();
			return true;

		default:
			break;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_next:// 点击N键事件处理
			if (!mIsCitySwitching) {
				if (mIsFirst) {
					mIsFirst = false;
					mPM25TextView.setText(" = PM2.5 /H ");
					mAQITextView.setText("    AQI ");
					mValueTextView.setText(mPM25Str);
					return;
				}
				mIsFirst = true;
				mPM25TextView.setText("    PM2.5 /H ");
				mAQITextView.setText(" = AQI ");
				mValueTextView.setText(mAQIStr);
				return;
			}
			selectCity();
			break;
		case R.id.btn_print:// 点击P键事件处理
			if (!mIsCitySwitching && mIsCanPrint) {
				startPaperAnimation();
				mIsFeedback = false;
				mIsCanPrint = false;
				return;
			}
			mIsCitySwitching = false;
			String city = mCityTextView.getText().toString().trim();
			if (city.equalsIgnoreCase("change city")) {
				mAQITextView.setVisibility(View.VISIBLE);
				mPM25TextView.setVisibility(View.VISIBLE);
				mValueTextView.setVisibility(View.VISIBLE);
				mCityTextView.setText(mBeforeCity);
				mCityTextView.setAnimation(null);
				return;
			} else if (city.equalsIgnoreCase("auto")) {
				mSetting.setCity("auto");
				// mCityTextView.setAnimation(null);
				// mCityTextView.setText(R.string.txt_detecting);
				requesLocation();
			} else {
				mSetting.setCity(city);
				mCityTextView.setAnimation(null);
				updateAQI_PM25(mSetting.getCity());
			}
			break;
		case R.id.btn_paper_share:// 点击分享键事件处理
			shareTo();
			break;
		default:
			break;
		}
	}

	public void onPause() {
		super.onPause();
		mAQIStr = null;// 暂停时，将此变量置空
		// 取消定位
		if (mPm25Geocoder != null)
			mPm25Geocoder.recordLocation(false);
	}

	protected void onResume() {
		super.onResume();
		if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_NONE) {
			Toast.makeText(this, R.string.net_error, Toast.LENGTH_SHORT).show();
			return;
		}
		if (mSetting.getCity().equalsIgnoreCase("auto")) {// 如果需要自动定位
			if (mSetting.getAutoCity().equals("")) {
				requesLocation();
			} else {
				String city = mSetting.getAutoCity();
				mCityTextView.setText(city);
				updateAQI_PM25(city);
				mCityTextView.setAnimation(null);
			}
		} else {
			String city = mSetting.getCity();
			mCityTextView.setText(city);
			if (TextUtils.isEmpty(mAQIStr)
					|| TextUtils.equals("error", mAQIStr.trim()))// 如果没有全局变量时才更新
				updateAQI_PM25(city);
			mCityTextView.setAnimation(null);
		}
	}

	/**
	 * 请求获取位置
	 */
	private void requesLocation() {
		if (mPm25Geocoder == null) {
			mPm25Geocoder = new PM25Geocoder(this, new CityNameStatus() {

				@Override
				public void update(String city) {
					enableButtonControls(true);
					// 有数据返回，停止定位
					if (mPm25Geocoder != null)
						mPm25Geocoder.recordLocation(false);
					if (TextUtils.isEmpty(city)) {// 未定位到城市,提示一下，返回
						Toast.makeText(PM25Activity.this,
								R.string.get_location_fail, Toast.LENGTH_SHORT)
								.show();
						mCityTextView.setText(R.string.txt_location_fail);
						mCityTextView.setAnimation(null);
						return;
					}
					L.d(TAG, "geo coder get city name:" + city);
					mSetting.setAutoCity(city);
					mCityTextView.setText(wrapFont(city));
					updateAQI_PM25(city);
					mCityTextView.setAnimation(null);
				}

				@Override
				public void showGpsOnScreenIndicator(boolean hasSignal) {
				}

				@Override
				public void hideGpsOnScreenIndicator() {
				}

				@Override
				public void detecting() {
					enableButtonControls(false);
					mAlphaAnim.setDuration(100L);
					mAlphaAnim.setRepeatCount(-1);
					mCityTextView.setText(R.string.txt_detecting);
					mCityTextView.setAnimation(mAlphaAnim);
					mAlphaAnim.start();
				}
			});
		}
		// 开始请求定位
		mPm25Geocoder.recordLocation(true);
	}

	/**
	 * 连续按两次返回键就退出
	 */
	private long firstTime;

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - firstTime < 3000) {
			finish();
		} else {
			firstTime = System.currentTimeMillis();
			Toast.makeText(this, R.string.press_again_exit, Toast.LENGTH_SHORT)
					.show();
		}
	}

}